package com.jieyun.core.config;

import java.util.Map;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.collect.Maps;
import com.jieyun.core.component.shiro.ShiroRealm;

import lombok.Data;

/**
 * shiro部分的配置内容
 * 
 * @author trek
 *
 */
@Configuration
public class ShiroConfig {
	
	// 这一部分会在后面添加Redis的支持
	/*@Value("${spring.redis.shiro.host}")
	private String host;
	@Value("${spring.redis.shiro.port}")
	private int port;
	@Value("${spring.redis.shiro.timeout}")
	private int timeout;
	@Value("${spring.redis.shiro.password}")
	private String password;
	 */
	
	
	
	@Data
	@ConfigurationProperties("shiro")
	@Configuration
	private static class ShiroPropertity{
		private Map<String,String> chain = Maps.newLinkedHashMap();
		private String loginUrl;
		private String successUrl;
	}
	
	/**
	 * 配置shiroFilter
	 * @param securityManager
	 * @return
	 */
	@Bean
	public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager,ShiroPropertity shiroPropertity) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		shiroFilterFactoryBean.setLoginUrl(shiroPropertity.getLoginUrl());
		shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroPropertity.getChain());
		return shiroFilterFactoryBean;
	}

	
	/**
	 * 自定义realm
	 * @return
	 */
	@Bean
	public ShiroRealm shiroRealm() {
		ShiroRealm myShiroRealm = new ShiroRealm();
		return myShiroRealm;
	}
	
	/**
	 * 安全管理器
	 * @return
	 */
	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(shiroRealm());
		// 自定义session管理 使用redis
		//securityManager.setSessionManager(sessionManager());
		// 自定义缓存实现 使用redis
		return securityManager;
	}

	// 自定义sessionManager
	/*@Bean
	public SessionManager sessionManager() {
		RedisSessionManager mySessionManager = new RedisSessionManager();
		return mySessionManager;
	}*/


	/**
	 * 开启shiro aop注解支持.使用代理方式;所以需要开启代码支持;
	 *
	 * @param securityManager
	 * @return
	 */
	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
		authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
		return authorizationAttributeSourceAdvisor;
	}

}
